<?php
/**
 * Created by dh2y.
 * Blog: http://blog.csdn.net/sinat_22878395
 * Date: 2020/2/5 18:56
 * For:
 */

namespace app\admin\controller\sys;


use app\admin\model\AuthRule;
use app\admin\service\sys\AuthRuleService;
use app\common\controller\BaseAdmin;

class Auth extends BaseAdmin
{

    public function index(){

        if ($this->request->isAjax()) {
            //获取搜索条件
            $data = $this->request->except(['page'], 'get');

            $model = new AuthRule();
            $list = $model->withSearch($this->searchFields($data), $this->searchData($data))
                ->order('id', 'desc')
                ->paginate($data['limit'], false);

            return $this->tableJson($list->getCollection(), $list->total());
        }
        return $this->fetch();
    }

    /**
     * 新建/编辑权限
     * @return string|\think\response\Json
     */
    public function edit(){
        if ($this->request->isAjax()){
            if ($this->request->isGet()){
                //树状菜单
                $menuList = AuthRuleService::allMenu();
                return json(['code' => 0, 'msg' => '操作成功', 'data' => $menuList]);
            }

            $data = $this->request->param();

            //编辑或者添加数据
            $scene = empty($data['id'])?'add':'edit';
            return json(AuthRuleService::storeRule($data,$scene));
        }

        $id = $this->request->get('id');
        if ($id){
            $list = AuthRule::where('id', $id)->find();
            $this->assign('list', $list);
        }

        //将添加的父级pid传到view
        $pid = $this->request->get('pid','');
        $this->assign('pid', $pid);

        return $this->fetch();
    }

    /**
     * 删除批量删除
     */
    public function remove(){
        if ($this->request->isAjax()){
            $ids = $this->request->param('ids');
            AuthRule::destroy($ids);
            $this->success('删除成功');
        }else{
            $this->error('非法请求');
        }
    }

    /**
     * 权限审核
     */
    public function change(){
        $id = $this->request->param('id');
        $model = AuthRule::find($id);
        $model->state = $this->request->param('state');
        if ($model->save()){
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * 更新权限菜单类型
     */
    public function menu(){
        $id = $this->request->param('id');
        $model = AuthRule::find($id);
        $model->menu = $this->request->param('menu');
        if ($model->save()){
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    /**
     * 获取权限结构数据
     */
    public function tree(){
        $tree = AuthRuleService::access(false);
        return json(['code' => 0, 'msg' => '操作成功', 'data' => $tree]);
    }

}